<script>
import { getItem, setItem, removeItem } from '@/utils/localStorage'
import { validUsername, validPassword } from '@/utils/validate'

export default {
  name: 'loginForm',
  data() {
    /*  验证用户名的校验函数 */
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) return callback(new Error('用户名长度必须大于3位'))
      callback()
    }
    /*  验证密码的校验函数 */
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) return callback(new Error('密码长度必须大于5位'))
      callback()
    }
    return {
      /* 表单数据对象 */
      loginForm: {
        username: '',
        password: ''
      },
      /* 表单规则对象 */
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '请输入用户名' },
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入密码' },
          { validator: validatePassword, trigger: 'blur' }
        ]
      },
      /* 是否记住用户名和密码 */
      remember: false,
      /* 登录按钮的loading状态 */
      loading: false,
      /* 密码框的类型 */
      passwordType: 'password',
      /* 重定向的参数 */
      redirect: undefined
    }
  },

  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    remember: {
      handler(newValue) {
        setItem('remember', newValue)
      }
    }
  },

  methods: {
    /* 用于持久化勾选复选框的回调函数 */
    rememberCheckbox() {
      const remember = getItem('remember')
      this.remember = remember === 'true'
    },

    /* 用于持久化用户名和密码的回调函数 */
    rememberLoginForm() {
      const loginForm = getItem('loginForm')
      if (loginForm) {
        this.loginForm = JSON.parse(loginForm)
      }
    },

    /* 点击密码框小眼睛icon图标的回调函数 */
    handleShowPwd() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password'
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    /* 点击登录按钮的回调函数 */
    async handleLogin() {
      const valid = await this.$refs.loginForm.validate().catch(error => error)
      if (!valid) return this.$message.warning('请完善登录信息')
      try {
        this.loading = true
        await this.$store.dispatch('user/login', this.loginForm)
        this.$message.success('登录成功')
        this.$router.push(this.redirect || '/')
        if (this.remember) {
          setItem('loginForm', JSON.stringify(this.loginForm))
        } else {
          removeItem('loginForm')
        }
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    }

  },

  created() {
    this.rememberLoginForm()
    this.rememberCheckbox()
  }

}
</script>

<template>
  <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
    <div class="title-container">
      <img src="../../assets/images/logo.png">
    </div>
    <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
      <el-input ref="username" v-model="loginForm.username" placeholder="请输入用户名"/>
    </el-form-item>

    <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
      <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="请输入密码" :show-password="false" @keyup.enter.native="handleLogin"/>
      <span class="show-pwd" @click="handleShowPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
    </el-form-item>

    <el-form-item class="checkbox">
      <el-checkbox v-model="remember">记住用户名</el-checkbox>
    </el-form-item>

    <el-button :loading="loading" type="primary" @click.native.prevent="handleLogin">登录</el-button>

  </el-form>
</template>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-form {
  position: relative;
  width: 520px;
  margin: 0 auto;
  overflow: hidden;
}

.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 10px;

  span {
    &:first-of-type {
      margin-right: 16px;
    }
  }
}

.el-button {
  width: 100%;
  height: 45px;
  margin-bottom: 30px;
  font-size: 20px;
}

.svg-container {
  padding: 6px 5px 6px 15px;
  color: $dark_gray;
  vertical-align: middle;
  width: 30px;
  display: inline-block;
}

.title-container {
  text-align: center;
  position: relative;
  margin-bottom: 20px;

  img {
    width: 400px;
    height: 80px;
  }
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  user-select: none;
}

.checkbox {
  border: 0 !important;
  background: unset !important;


  .el-checkbox {
    color: $bg;
  }
}
</style>
